package com.rectcircle.wechat.util;

import com.rectcircle.wechat.api.BasicApi;
import com.rectcircle.wechat.exception.ApiRequestErrorException;
import com.rectcircle.wechat.exception.ConfigException;
import com.rectcircle.wechat.vo.AccessToken;

/**
 * 微信缓存工具
 * 缓存AccessToken、JsApiTicket的静态工具类<br>
 * 使用前需要调用setParameter设置参数<br>
 * 以后获取accesstoken直接调用getAccessToken()即可<br>
 * 如果参数不进行设置或设置有误，将抛出ApiRequestErrorException<br>
 * 
 * @author RectCircle
 * @version 0.1<br>
 * 2016年7月14日-下午5:39:26<br>
 * Copyright (c) 2016 RectCircle-版权所有<br>
 *
 */
public class WechatCache {
	
	private static String appid = null;
	private static String appsecret = null;
	
	private static AccessToken accessToken = null;
	
	/**
	 * 设置缓存参数
	 * @param appid
	 * @param appsecret
	 */
	public static void setParameter(String appid, String appsecret){
		WechatCache.appid = appid;
		WechatCache.appsecret = appsecret;
	}
	
	
	/**
	 * 获得accesstoken（失效自动刷新）<br>
	 * 未设置参数，或请求失败将抛出异常ApiRequestErrorException<br>
	 * 
	 * @return acessToken字符串
	 * @throws ApiRequestErrorException 请求api出错
	 * @throws ConfigException 参数错误
	 */
	public static String getAccessToken() throws ApiRequestErrorException, ConfigException{
		if(appid==null||appsecret==null){
			throw new ConfigException("未设置参数appid:"+appid+", appsecret:"+appsecret+" 请检查参数");
		} 
		
		if(accessToken == null) {
			accessToken = BasicApi.obtainAccessToken(appid, appsecret);
			accessToken.setUpdateTime(System.currentTimeMillis());
			return accessToken.getAccess_token();
		} else {
			long now = System.currentTimeMillis(); 
			
			if((now - accessToken.getUpdateTime())/1000 > accessToken.getExpires_in()+60){
				accessToken = BasicApi.obtainAccessToken(appid, appsecret);
				accessToken.setUpdateTime(System.currentTimeMillis());
			}
			return accessToken.getAccess_token();
		}
		 
	}
	
}
